<template>
  <!-- name: 上传文件的字段名，data：除了文件其他的需要上传的字段名 -->
  <el-upload
    ref="uploadRef"
    drag
    :action="action"
    multiple
    :headers="headers"
    :name="name"
    :data="data"
    :on-success="uploadSuccess"
    :on-error="uploadError"
  >
    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
    <div class="el-upload__text">
      Drop file here or <em>click to upload</em>
    </div>
    <template #tip>
      <div class="el-upload__tip">
        jpg/png files with a size less than 500kb
      </div>
    </template>
  </el-upload>
</template>

<script setup>
  import { uploadImageAction } from '@/api/image.js'
  import { getToken, toast } from '@/utils'
  import { ref } from 'vue'
  const token = getToken()

  const emit = defineEmits(['success', 'error'])
  const props = defineProps({
    data: Object,
    name: {
      type: String,
      default: 'img',
    },
    headers: {
      type: Object,
      default: () => ({ token: getToken() }),
    },
    action: {
      type: String,
      default: uploadImageAction,
    },
  })

  function uploadSuccess(response, uploadFile, uploadFiles) {
    emit('success', {
      response,
      uploadFile,
      uploadFiles,
    })
  }
  function uploadError(error, uploadFile, uploadFiles) {
    let msg = JSON.parse(error.message).msg || '上传失败'
    toast(msg, 'error')
  }

  const uploadRef = ref(null)
  function clearFiles() {
    uploadRef.value.clearFiles()
  }

  defineExpose({
    clearFiles,
  })
</script>
